import React, { PureComponent } from 'react';
import G2 from '@antv/g2';
import { DataSet } from '@antv/data-set';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import classNames from 'classnames';
import { isEqual } from 'lodash';
import { isNotEmptyArray } from '../../../utils/utils';
import '../index.less';

// import styles from './index.less';

// const { DataView } = DataSet;

export default class BasePie extends PureComponent {
  /*static defaultProps = {};

  state = {};

  componentWillMount() {

  }*/

  componentDidMount() {
    this.initChart();
    window.addEventListener('resize', this.resize);
  }

  componentWillReceiveProps(nextProps) {
    if (!isEqual(this.props, nextProps)) {
      this.initChart(nextProps);
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
    this.data = null;
    if (this.chart) {
      this.chart.destroy();
    }
    this.resize.cancel();
  }
  @Bind()
  @Debounce(200)
  resize() {
    if (!this.node) {
      return;
    }
    this.renderChart();
  }

  /**
   * 延迟加载，避免样式还没渲染完成导致 this.node.clientHeight 获取时值不对
   */
  @Debounce(10)
  initChart(nextProps) {
    const {
      x, y, data = [],
    } = nextProps || this.props;

    if (!x || !y) {
      throw new Error('x or y not defined');
    }
    if (!isNotEmptyArray(data)) {
      return;
    }
    this.data = data.map(e => ({
      item: e[x],
      value: Number(e[y]),
    }));
    this.renderChart(nextProps);
  }

  handleRef = (n) => {
    this.node = n;
  }

  renderChart(nextProps) {
    const {
      height = this.node.clientHeight, hasLegend = false, legendPos = 'left', offsetY, offsetX,
      animate = true, padding = [30, 30, 30, 48],
    } = nextProps || this.props;

    if (this.chart) {
      this.chart.clear();
    }
    if (this.node) {
      this.node.innerHTML = '';
    }

    const ds = new DataSet();
    const dv = ds.createView();
    // const dv = new DataView();
    dv.source(this.data).transform({
      type: 'percent',
      field: 'value',
      dimension: 'item',
      as: 'percent', // 结果存储在 percent 字段
    });
    const chart = new G2.Chart({
      container: this.node,
      forceFit: true,
      height,
      animate,
      padding,
    });
    chart.source(dv, {
      percent: {
        formatter: val => `${(val * 100).toFixed(1)}%`,
      },
    });
    chart.coord('theta'); //一种半径固定的极坐标系，常用于饼图。
    chart.tooltip({
      showTitle: false,
    });
    if (hasLegend) {
      chart.legend({
        position: legendPos, // 设置图例的显示位置
        offsetY,
        offsetX,
      });
    }
    chart.intervalStack()
      .position('percent')
      .color('item')
      .label('percent', {
        offset: -30,
        // autoRotate: false,
        textStyle: {
          rotate: 0,
          textAlign: 'center',
          shadowBlur: 2,
          shadowColor: 'rgba(0, 0, 0, .45)',
        },
      })
      .tooltip('item*percent', (item, percent) => ({
        name: item,
        value: `${(percent * 100).toFixed(1)}%`,
      }))
      .style({
        lineWidth: 1,
        stroke: '#fff',
      });

    this.chart = chart;
    chart.render();
  }

  render() {
    const { data } = this.props;

    const noDataClass = classNames({ noData: !isNotEmptyArray(data) });
    return (
      <div ref={this.handleRef} className="chart">
        <div className={noDataClass}>暂无数据</div>
      </div>
    );
  }
}
